#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

#define M 512
#define N 1024
#define K 2048

// 生成随机矩阵
void generate_random_matrix(double *matrix, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i * cols + j] = (double)rand() / RAND_MAX; // 生成0-1之间的随机数
        }
    }
}

// 矩阵乘法
void matrix_multiply(const double *A, const double *B, double *C, 
                     int m, int n, int k) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < k; j++) {
            double sum = 0.0;
            for (int p = 0; p < n; p++) {
                sum += A[i * n + p] * B[p * k + j];
            }
            C[i * k + j] = sum;
        }
    }
}

// 打印矩阵（前3x3部分）
void print_matrix_part(const double *matrix, int rows, int cols, const char *name) {
    printf("Matrix %s (%d x %d):\n", name, rows, cols);
    int print_rows = rows > 3 ? 3 : rows;
    int print_cols = cols > 3 ? 3 : cols;
    
    for (int i = 0; i < print_rows; i++) {
        for (int j = 0; j < print_cols; j++) {
            printf("%8.4f ", matrix[i * cols + j]);
        }
        printf("...\n");
    }
    printf("...\n\n");
}

double get_current_time() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

int main() {
    // 设置随机种子
    srand(time(NULL));
    
    // 分配矩阵内存
    double *A = (double *)malloc(M * N * sizeof(double));
    double *B = (double *)malloc(N * K * sizeof(double));
    double *C = (double *)malloc(M * K * sizeof(double));
    
    // 生成随机矩阵
    generate_random_matrix(A, M, N);
    generate_random_matrix(B, N, K);
    
    // 记录开始时间
    double start_time = get_current_time();
    
    // 计算矩阵乘积
    matrix_multiply(A, B, C, M, N, K);
    
    // 记录结束时间
    double end_time = get_current_time();
    
    // 打印结果
    print_matrix_part(A, M, N, "A");
    print_matrix_part(B, N, K, "B");
    print_matrix_part(C, M, K, "C");
    printf("Time taken for multiplication: %.6f seconds\n", end_time - start_time);
    
    // 释放内存
    free(A);
    free(B);
    free(C);
    
    return 0;
}